<template>
  <!-- 这是一个无渲染组件，只处理逻辑 -->
</template>

<script setup>
import { onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import pageStack from '../utils/pageStack'

const router = useRouter()

// 处理App返回逻辑
const handleAppBack = () => {
  // console.log('当前页面栈长度:', pageStack.getLength())
  // console.log('是否可以返回:', pageStack.canGoBack())
  
  if (pageStack.canGoBack()) {
    const previousPage = pageStack.handleBack()
    // console.log('返回上一页:', previousPage)
    if (previousPage) {
      router.push(previousPage.path)
    }
  } else {
    // console.log('退出应用')
    // 如果只有一个页面，则退出应用
    if (typeof plus !== 'undefined' && plus.runtime) {
      plus.runtime.quit()
    }
  }
}

// 添加触摸手势检测
let startX = 0
let startY = 0
let endX = 0
let endY = 0

const handleTouchStart = (e) => {
  startX = e.touches[0].clientX
  startY = e.touches[0].clientY
}

const handleTouchEnd = (e) => {
  endX = e.changedTouches[0].clientX
  endY = e.changedTouches[0].clientY
  
  const deltaX = endX - startX
  const deltaY = endY - startY
  
  // 检测从左边缘向右的滑动（侧滑返回）
  if (deltaX > 50 && Math.abs(deltaY) < 100 && startX < 50) {
    // console.log('检测到侧滑返回手势')
    handleAppBack()
  }
}



let backButtonHandler = null
let popGestureHandler = null

onMounted(() => {
  // 延迟初始化，确保plus对象可用
  setTimeout(() => {
    if (typeof plus !== 'undefined') {
      // console.log('检测到App环境，初始化返回处理')
      
      // 监听返回按钮事件
      backButtonHandler = () => {
        // console.log('返回按钮被点击')
        handleAppBack()
      }
      plus.key.addEventListener('backbutton', backButtonHandler)
      
      // 监听侧滑返回事件
      try {
        const currentWebview = plus.webview.currentWebview()
        if (currentWebview) {
          popGestureHandler = () => {
            // console.log('侧滑返回被触发')
            handleAppBack()
          }
          currentWebview.addEventListener('popGesture', popGestureHandler)
        }
      } catch (error) {
        console.log('侧滑事件监听失败:', error)
      }
    }
  }, 1000)
  
  // 添加触摸事件监听
  document.addEventListener('touchstart', handleTouchStart, { passive: true })
  document.addEventListener('touchend', handleTouchEnd, { passive: true })
})

onUnmounted(() => {
  // 清理事件监听器
  if (typeof plus !== 'undefined') {
    if (backButtonHandler) {
      plus.key.removeEventListener('backbutton', backButtonHandler)
    }
    if (popGestureHandler) {
      try {
        const currentWebview = plus.webview.currentWebview()
        if (currentWebview) {
          currentWebview.removeEventListener('popGesture', popGestureHandler)
        }
      } catch (error) {
        console.log('清理侧滑事件监听失败:', error)
      }
    }
  }
  
  // 清理触摸事件监听
  document.removeEventListener('touchstart', handleTouchStart)
  document.removeEventListener('touchend', handleTouchEnd)
})
</script>
